'''
Created on Dec 5, 2009

@author: bodnaria
'''
from google.appengine.ext import db
from User import getUserByEmail
from google.appengine.api import mail
from error import UserError
import hashlib
import time

def deleteKey(key):
    temp_users = TempUser.all()
    matching_users = filter(lambda x:x.uniquekey == key, temp_users)
    if len(matching_users) < 1:
        raise UserError.UserError("error")
    
    matching_users[0].delete()

def getUserByKey(key):
    current_users = TempUser.all()
    matching_users = filter(lambda x:x.uniquekey == key, current_users)
    if len(matching_users) < 1:
        raise UserError.UserError("No such hash.")
    
    return matching_users[0]
    
def generateInviteLink(hashed):
    link = "http://cs440x-bookbook.appspot.com/validate_link?key="+hashed 
    return link

def sendEmail(to_addr, hashed):
    message = mail.EmailMessage()
    message.subject = "Welcome to cs440x-bookbook!"
    message.sender = "cs440x.bookbook@gmail.com"
    message.to = to_addr
    message.body = """
        I've invited you to CS440x-bookbook.com!

        To accept this invitation, click the following link,
        or copy and paste the URL into your browser's address
        bar:

        % s
        """ % generateInviteLink(hashed)

    message.send()
    

def createTempUser(a_username, an_email):
    from User import User
    # Check for duplicate usernames or email address and error if we find one.
    if User.get_by_key_name(a_username) != None:
        raise UserError.UserError("badUsername")
    
    if getUserByEmail(an_email) == True:
        raise UserError.UserError("badSecondEmail")
    
    
    hashed =  hashlib.sha256(an_email + str(time.time()) ).hexdigest()   
    sendEmail(an_email, hashed)
    
    temp_user = TempUser(
                         username = a_username, 
                         email = an_email,
                         uniquekey = hashed,
                         key_name = an_email
                         )
    temp_user.put()
    
    return temp_user
    
class TempUser(db.Model):
    username = db.StringProperty(required=True)
    email = db.EmailProperty(required=True)
    uniquekey = db.StringProperty(required=True)
